package utils

import (
	"crypto/md5"
	"fmt"
	"net"
	"net/http"
	"strings"

	"github.com/go-ini/ini"
)

// instance
var instance *ini.File

// GetConfig
// 获取配置
//
//	@param section
//	@param key
//	@return string
func GetConfig(section string, key string, defaultValue string) string {
	if instance == nil {
		f, _ := ini.Load("config.ini")
		instance = f
	}
	v := instance.Section(section).Key(key).String()
	if v == "" && defaultValue != "" {
		return defaultValue
	}
	return v
}

// GetAddress
// 获取监听地址
//
//	@return []string
func GetListenAddress() []string {
	address := GetConfig("init", "addr", "")
	addressArr := strings.Split(address, "://")
	if addressArr[0] == "https" {
		return []string{addressArr[0], addressArr[1]}
	}
	var addr string
	if len(addressArr) > 1 {
		addr = addressArr[1]
	} else {
		addr = addressArr[0]
	}
	return []string{"http", addr}
}

// GetProxy
// 获取代理服务器
//
//	@return string
func GetProxyServer() string {
	proxy := GetConfig("proxy", "addr", "")
	if proxy == "" {
		return ""
	}
	proxyArr := strings.Split(proxy, "://")
	if proxyArr[0] != "http" && proxyArr[0] != "https" {
		return "http://" + proxyArr[0]
	}

	return proxy
}

// Md5
//
//	@param text
//	@return string
func Md5(text string) string {
	hash := md5.New()
	hash.Write([]byte(text))
	byteData := hash.Sum(nil)
	return fmt.Sprintf("%x", byteData)
}

// GetClientIP
// 获取客户端IP
//
//	@param r
//	@return string
func GetClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}
	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}
	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}
	return ""
}
